package com.pro01.backend.controller;

import com.pro01.backend.pojo.PageResult;
import com.pro01.backend.pojo.Result;
import com.pro01.backend.pojo.TorrentClass;
import com.pro01.backend.service.PromotionService;
import com.pro01.backend.service.TorrentService;
import com.pro01.backend.utils.JwtUtil;
import com.pro01.backend.utils.TokenUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 后台种子管理接口 (仅限管理员)
 */
@RestController
@RequestMapping("/admin/torrents")
public class AdminTorrentController {

    @Autowired
    private TorrentService torrentService;
    @Autowired
    private PromotionService promotionService;

    /**
     * 提取 JWT 中的 claims
     */
//    private Map<String, Object> getClaims(HttpServletRequest request) {
//        String token = request.getHeader("Authorization");
//        return JwtUtil.parseToken(token);
//    }

    /**
     * 判断当前用户是否为管理员
     */
//    private boolean isAdmin(HttpServletRequest request) {
//        Map<String, Object> claims = getClaims(request);
//        return claims != null && "ADMIN".equals(claims.get("role"));
//    }

    /**
     * 判断当前用户是否为管理员
     */
    private boolean isAdmin(HttpServletRequest request) {
        try {
            String role = TokenUtil.getRole(request); // ✅ 直接从工具类取角色
            return "ADMIN".equals(role);
        } catch (Exception e) {
            return false; // token 无效或缺失
        }
    }

    /**
     * 分页查看所有种子（包含所有状态）
     */
    @GetMapping
    public Result<PageResult<TorrentClass>> getAllTorrents(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize,
            HttpServletRequest request) {
        if (!isAdmin(request)) {
            return Result.error("无权限访问，仅管理员可用！");
        }
        PageResult<TorrentClass> pageResult = torrentService.getAllTorrentsForAdmin(pageNum, pageSize);
        return Result.success(pageResult);
    }

    /**
     * 删除种子（逻辑删除，将 status 改为 DELETED）
     */
    @DeleteMapping("/{torrentId}")
    public Result<?> deleteTorrent(@PathVariable Long torrentId, HttpServletRequest request) {
        if (!isAdmin(request)) {
            return Result.error("无权限操作，仅限管理员！");
        }

        boolean success = torrentService.adminDeleteTorrent(torrentId);
        return success ? Result.success("种子删除成功") : Result.error("种子删除失败");
    }

    /**
     * 管理员根据文件名模糊查询种子
     */
    @GetMapping("/search")
    public Result<PageResult<Map<String, Object>>> searchTorrentsByName(@RequestParam("keyword") String keyword,
                                                                        @RequestParam(defaultValue = "1") int pageNum,
                                                                        @RequestParam(defaultValue = "10") int pageSize,
                                                                        HttpServletRequest request) {
        if (!isAdmin(request)) {
            return Result.error("无权限访问，仅管理员可用");
        }

        if (pageSize > 50) {
            pageSize = 50;
        }

        try {
            PageResult<Map<String, Object>> pageResult = torrentService.searchTorrentsWithUploader(keyword, pageNum, pageSize);
            return Result.success(pageResult);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("搜索失败：" + e.getMessage());
        }
    }

    /**
     * 管理员根据用户名模糊查询种子
     */
    @GetMapping("/search-by-uploader")
    public Result<PageResult<Map<String, Object>>> searchTorrentsByUploader(@RequestParam("uploaderName") String uploaderName,
                                                                            @RequestParam(defaultValue = "1") int pageNum,
                                                                            @RequestParam(defaultValue = "10") int pageSize,
                                                                            HttpServletRequest request) {
        if (!isAdmin(request)) {
            return Result.error("无权限访问，仅管理员可用");
        }

        if (pageSize > 50) {
            pageSize = 50;
        }

        try {
            PageResult<Map<String, Object>> pageResult = torrentService.searchTorrentsByUploader(uploaderName, pageNum, pageSize);
            return Result.success(pageResult);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("搜索失败：" + e.getMessage());
        }
    }

    /**
     * 管理员根据状态模糊查询种子
     */
    @GetMapping("/search-by-status")
    public Result<PageResult<Map<String, Object>>> searchTorrentsByStatus(@RequestParam("status") String status,
                                                                          @RequestParam(defaultValue = "1") int pageNum,
                                                                          @RequestParam(defaultValue = "10") int pageSize,
                                                                          HttpServletRequest request) {
        if (!isAdmin(request)) {
            return Result.error("无权限访问，仅管理员可用");
        }

        if (pageSize > 50) {
            pageSize = 50;
        }

        // 校验 status 合法性
        if (!"ACTIVE".equalsIgnoreCase(status) && !"DELETED".equalsIgnoreCase(status)) {
            return Result.error("状态参数错误，只能是 ACTIVE 或 DELETED");
        }

        try {
            PageResult<Map<String, Object>> pageResult = torrentService.searchTorrentsByStatus(status.toUpperCase(), pageNum, pageSize);
            return Result.success(pageResult);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("搜索失败：" + e.getMessage());
        }
    }

    /**
     * 接下来是种子促销逻辑
     */
    // 设置促销
    @PostMapping("/promote/{torrentId}")
    public Result<?> promoteTorrent(@PathVariable Long torrentId,
                                    @RequestParam("type") String type,
                                    @RequestParam("hours") int hours,
                                    HttpServletRequest request) {
        if (!isAdmin(request)) {
            return Result.error("无权限操作！");
        }

        try {
            if (!List.of("FREE", "DOUBLE_UPLOAD", "SEED_BONUS").contains(type)) {
                return Result.error("无效的促销类型");
            }
            boolean success = torrentService.promoteTorrent(torrentId, type, hours);
            return success ? Result.success("促销设置成功！") : Result.error("促销设置失败！");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("促销失败：" + e.getMessage());
        }
    }

    // 取消促销
    @PutMapping("/promotion/cancel/{torrentId}")
    public Result<?> cancelPromotion(@PathVariable Long torrentId, HttpServletRequest request) {
        if (!isAdmin(request)) {
            return Result.error("无权限操作，仅管理员可用！");
        }
        try {
            torrentService.cancelPromotion(torrentId);
            return Result.success("取消促销成功！");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("取消促销失败：" + e.getMessage());
        }
    }

    // 查询促销历史
    @GetMapping("/promotion/history")
    public Result<PageResult<Map<String, Object>>> getPromotionHistory(
            HttpServletRequest request,
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize) {

        if (!isAdmin(request)) {
            return Result.error("无权限访问，仅管理员可用！");
        }

        PageResult<Map<String, Object>> history = promotionService.getPromotionHistory(pageNum, pageSize);
        return Result.success(history);
    }
}
